<script setup>
import { User, Lock, CircleCheck } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { userLoginService, userGetCaptchaService } from "@/api/user/user.js";
import { useUserStore } from "@/stores";
import { useRouter } from "vue-router";

let loadingCaptcha = ref(false);
// 初始化验证码值并获取验证码
const codeValue = ref();
onMounted(async () => {
  await getCode();
});

// 获取验证码的函数
const getCode = async () => {
  loadingCaptcha.value = true;
  const { data } = await userGetCaptchaService();
  codeValue.value = data.codeValue;
  formModel.value.codeKey = data.codeKey;
  console.log(data);
  loadingCaptcha.value = false;
};

// 表单数据对象
const formModel = ref({
  username: "",
  password: "",
  captcha: "",
  codeKey: "",
});

// 表单校验规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 10, message: "用户名必须是5-10位的字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
  ],
  captcha: [
    { required: true, message: "请输入图形验证码", trigger: "blur" },
    {
      pattern: /^\S{4}$/,
      message: "验证码必须是4位的非空字符",
      trigger: "blur",
    },
  ],
};

// 表单引用
const form = ref();

// 重置表单
const reset = () => {
  formModel.value = {
    username: "",
    password: "",
    captcha: "",
    codeKey: "",
  };
};

// 登录逻辑处理
let loadingLogin = ref(false);
const userStore = useUserStore();
const router = useRouter();
console.log(userStore);

/**
 * 登录功能实现。
 * 无参数。
 * 无显式返回值，但会进行登录操作，并在成功或失败后有相应的提示。
 */
const login = async () => {
  loadingLogin.value = true;
  try {
    await form.value.validate(); // 验证表单
    console.log("开始登录");
    const res = await userLoginService(formModel.value); // 执行登录服务
    console.log(res);
    userStore.setToken(res.data.token); // 登录成功后，设置用户token
    ElMessage.success("登录成功");
    router.push("/"); // 重定向到首页
    await userStore.getUserInfo();
    await userStore.handleFilteredRoutes();
  } catch (error) {
    console.error("登录失败", error);
    ElMessage.error("登录失败");
  } finally {
    loadingLogin.value = false; // 无论登录成功或失败，最后都隐藏加载状态
  }
};
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        :model="formModel"
        :rules="rules"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formModel.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
          ></el-input>
        </el-form-item>
        <el-row justify="space-between">
          <el-col :span="18">
            <el-form-item prop="captcha">
              <el-input
                name="captcha"
                :prefix-icon="CircleCheck"
                placeholder="图形验证吗"
                v-model="formModel.captcha"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="6"
            style="display: flex; justify-content: flex-end"
            @click="getCode"
          >
            <img
              :src="codeValue"
              alt=""
              class="image border"
              v-if="codeValue"
            />
            <el-button :loading="loadingCaptcha" class="image" v-if="!codeValue"
              >点击获取</el-button
            >
          </el-col>
        </el-row>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="login"
            :loading="loadingLogin"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url("@/assets/logo2.png1") no-repeat 60% center / 240px auto,
      url("@/assets/logo2.png") no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
.image {
  width: 80px;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
  display: flex;
  align-items: center;
  color: #666;
  background: #e8f0fe;
  justify-content: center;
}
.border {
  border: #e8f0fe 1px solid;
}
</style>
